<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/5/23 0023
 * Describe: 订单管理类.
 */
namespace app\api\controller\lishidai;
use app\common\model\Order as orderModel;
use app\common\model\User;
use think\Db;
use app\common\controller\order\Orderget;

class Order extends Base
{
    /**
     * 订单还款接口
     * BindCard.applyRepay.
     * order_sn	string	是	订单唯一编号
     * repay_type	integer	是	0：仅还当期，1，分期业务全额还款
     * verify_code	string	否	扣款验证码，当已发送验证码之后再次请求提交
     * repay_periods	array	否	还款期数.
     */
    public function applyRepay()
    {
        //验证参数
        $param = input('');
        \Think\Log::record('立时贷 还款数据 '.json_encode($param));
        $postData = json_decode($param['args'], true);
        $result = $this->validate($postData, 'Order.applyRepay');
        if ($result !== true) {
            errorResult($result);
        }
        $order = Db::table('xb_loans_applylist')->where(['OrderSn' => $postData['order_sn']])->find();
        if (!$order) {
            errorResult('订单信息不存在');
        }
        if ($order['LoanStatus'] == '3') {
            //		   给立时代返回是吧数据
            $reuslt = array(
                           'status' => '1',
                           'message' => '订单已经还款成功 请勿重复还款',
                           'response' => [
                           'repay_result' => '200',
                           ],
                    );
            echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
            die;
        }
        //		p($order);die;
        $Orderget = new Orderget();
        $get_days_fakuan = $Orderget->get_days_fakuan(strtotime(date('Y-m-d'), time()), strtotime($order['YyFkTime']), $order);
        if ($postData['repay_type'] == '0') {//repay_type 0：仅还当期，1，分期业务全额还款
            //			根据商品获取商品信息  其实就是获取几个开关
            $get_goods = $Orderget->get_goods($order['ProductID']);
            if ($get_days_fakuan['datas'] == 0) { //正常客户展期
                //				根据产品的展期开关判断
                if ($get_goods['Status'] == '0') {
                    show_error_api('该类型订单不许与展期');
                }
            } else {//逾期客户展期
                if ($get_goods['Statusyuqi'] == '0') {
                    show_error_api('该类型订单不许与展期');
                }
            }
        }
        $user = Db::table('xb_mem_info')->where('ID', $order['UserID'])->find(); //用户数据
        $ret = Db::table('xb_renzen_bank')->where('UserID', $order['UserID'])->find();
        if ($ret) {
            $data['BankNo'] = $ret['BankNo']; //银行卡号
        } else {
            //		   给立时代返回是吧数据
            $reuslt = array(
                           'status' => '1',
                           'message' => '银行卡信息获取失败',
                           'response' => [
                           'repay_result' => '10000',
                           ],
                    );

            echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
        }
        if ($order) {
            $data['OrderSn'] = $order['OrderSn']; //applylist 订单号
            $Payceshi = $Orderget->get_Payceshi(); //获取支付环境
            if ($Payceshi == '1') {
            	 $orderModelObj = new orderModel();
                $data['Money'] = $orderModelObj->getOrderShould($order); //还款   应还金额
            } else {
                $data['Money'] = '0.01'; //放款金额
            }
        } else {
            //		   给立时代返回是吧数据
            $reuslt = array(
                           'status' => '1',
                           'message' => '用户订单获取失败',
                           'response' => [
                           'repay_result' => '10000',
                           ],
                    );

            echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
        }
        $changpay = new \changpay\ChangPay();
        $data['PartnerId'] = $Orderget->get_changpay(); //获取商户号
        $data['userId'] = $order['UserID']; //用户标志
        $data['type'] = '1'; //还款类型 1 还款 2续期
//      p($data);die;
        $datas = $changpay->changjie_bank($data);
        if ($datas['AcceptStatus'] == 'S') {
            //		   给立时代返回是吧数据
            $reuslt = array(
                           'status' => '1',
                           'message' => '还款申请提交成功, 还款成功后通知平台',
                           'response' => [
                           'repay_result' => '100',
                           ],
                    );

            echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
        } else {
            //		   给立时代返回是吧数据
            $reuslt = array(
                           'status' => '1',
                           'message' => $datas['RetMsg'],
                           'response' => [
                           'repay_result' => '10000',
                           ],
                    );

            echo json_encode($reuslt, JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 订单待确认页.
     *
     * http://xjdd.huakodai.cn/api.php/lishidai/order/waitingConfirm?user_name=宋林博&user_phone=15239626761&user_idcard=412824199207222617&order_sn=KY652950842106081280&return_url=http://www.baidu.com
     */
    public function waitingConfirm()
    {
        if (request()->isAjax()) {
            //验证参数
            $postData = Request()->only('orderId,isLoanAgree,return_url');
			
			\Think\Log::record('立时贷 确认用款数据提交'.json_encode($postData));
            $result = $this->validate($postData, 'Order.waitingConfirm');
            if ($result !== true) {
                return ajaxErrorResult($result);
            }
            //检测用户是否同意借款协议
            if ($postData['isLoanAgree'] != 1) {
                return ajaxErrorResult('请点击同意借款协议');
            }
            //处理订单打款
            $orderModelObj = new orderModel();
            $result = $orderModelObj->orderLoan($postData['orderId']);
            if ($result['code'] == '1') {
                return ajaxSuccessResult(['url' => $postData['return_url'].'?type=success&title=操作成功'], $result['msg']);
            } else {
                return ajaxErrorResult(['url' => $postData['return_url'].'?type=success&title=操作成功'], $result['msg']);
            }
        }

        //获取订单详情渲染页面
        $param = input();
		\Think\Log::record('立时贷 确认用款页面数据'.json_encode($param));
        reset($param);
        $first_key = key($param);
        $result = explode('&', $first_key);
        $temp = [];
        foreach ($result as $k => $v) {
            $temp[substr($v, 0, strrpos($v, '='))] = str_replace('_', '.', substr($v, strripos($v, '=') + 1));
        }
        //		p($temp);die;
        $orderData = db('loans_applylist')->alias('a')
        ->join('xb_mem_info i', 'a.UserID = i.ID', 'left')
        ->where(['a.OrderSn' => $temp['order_sn'], 'a.LoanStatus' => 1, 'i.IDCard' => $temp['user_idcard'], 'Mobile' => $temp['user_phone']])
        ->field('a.*,i.TrueName')
        ->find();
        $this->assign('orderData', $orderData);
        $this->assign('return_url', $temp['return_url']);
        return view();
    }

    /**
     * 借款试算接口.
     */
    public function loanCalculate()
    {
        //验证参数
        $param = input('');
        $postData = json_decode($param['args'], 1);
        $result = $this->validate($postData, 'Order.loanCalculate');
        if ($result !== true) {
            errorResult($result);
        }
        //检测借款金额是否可正常借款
        $orderModelObj = new orderModel();
        $loanOrderData = $orderModelObj->getMoneyOrderInfo(($postData['loan_amount'] / 100).'.00');
        if (!$loanOrderData) {
            errorResult('产品未上架或不存在');
        }
        $temp = [
            'service_fee' => $loanOrderData['GuanliCost'] * 100, //服务费，单位: 分，例如： 10000
            'service_fee_desc' => '服务费', //服务费说明，例如：包含30%风控服务费， 40%信息认证费
            'interest_fee' => $loanOrderData['nianhualilv'], //利息
            'receive_amount' => $loanOrderData['daozhang'] * 100, //到账金额
            'repay_amount' => $loanOrderData['daoqiyinghua'] * 100, //应还总额
            'repay_plan' => [], //预计还款计划, 数组内每个元素数据结构如下表。(系统仅为1期 所有放空)
        ];
        successResult($temp);
    }

    /**
     * 拉取还款计划.
	 * 
	 * 订单还款结束 调用此接口
     */
    public function getRepayplan()
    {
        //验证参数
        $param = input('');
        $postData = json_decode($param['args'], 1);
        $result = $this->validate($postData, 'Order.getRepayplan');
        if ($result !== true) {
            errorResult($result);
        }
        //获取订单信息
        $orderModelObj = new orderModel();
        $orderData = $orderModelObj->getIdOrderInfo($postData['order_sn']);
        if (!$orderData) {
            errorResult('未获取订单数据');
        }
        //获取订单应还款总额
        $totalAmount = $orderModelObj->getOrderShould($orderData);
        //获取订单部分还款金额
        $alreadyPaid = $orderModelObj->getOrderPartMoney($orderData);
        //获取订单罚息
        $interest = $orderModelObj->getOrderPenalty($orderData);
        //获取订单还款时间
        $repaymentOrder = $orderModelObj->getRepaymentOrder($orderData['ID']);
        $temp = [
            'order_sn' => $orderData['OrderSn'], //订单唯一编号
            'total_amount' => $totalAmount * 100, //借款总额; 单位: 分 本期还款本金期数相加 principle相加 (计算了应还总额，扣除部分还款等，并加上了逾期金额)
            'total_svc_fee' => $orderData['Interest'] * 100, //总服务费; 单位: 分
            'received_amount' => $orderData['AdoptMoney'] * 100, //到账金额; 单位: 分
            'already_paid' => $alreadyPaid * 100, //已还金额; 单位: 分
            'total_period' => 1, //总期数 （系统内置只1期 所以写1）
            'finish_period' => '', //已还期数
            'borrow_dealine' => $orderData['ApplyDay'], //借款期限 订单借款期限
            'borrow_unit' => 1, //借款期限单位 1 天 2 月 3 年
            'repayment_plan' => [ //具体还款计划数组
                'period_no' => 1,
                'principle' => $totalAmount * 100, //本期还款本金; 单位: 分
                'interest' => $interest * 100, //本期还款利息; 单位: 分
                'service_fee' => $orderData['Interest'] * 100, //本期服务费用; 单位: 分
                'bill_status' => ($orderData['LoanStatus'] == 3) ? 1 : 0, //本期账单状态; -1: 未出账; 0: 未还款; 1: 已还款
                'total_amount' => $totalAmount * 100, //本期还款总额; 单位: 分
                'already_paid' => $alreadyPaid * 100, //本期已还金额; 单位: 分
                'loan_time' => strtotime($orderData['YyFkTime']), //实际起息时间
                'due_time' => strtotime($orderData['YyFkTime']), //最迟还款时间（精确到秒超过该时间就算逾期）
                'can_pay_time' => strtotime($orderData['YyFkTime']), //可以还款时间
                'finish_pay_time' => !empty($repaymentOrder['HkTime']) ? strtotime($repaymentOrder['HkTime']) : '', //实际完成还款时间
                'overdue_day' => $orderModelObj->isOrderOverdue($orderData), //逾期天数
                'overdue_fee' => $interest * 100, //逾期费用; 单位: 分
                'period_fee_desc' => '',
                'pay_type' => $orderModelObj->getPayType(!empty($repaymentOrder) ? $repaymentOrder['Type'] : ''),
            ],
        ];
        successResult($temp);
    }

    /**
     * 拉取订单状态
     */
    public function getOrderStatus()
    {
        //验证参数
        $param = input('');
        $postData = json_decode($param['args'], 1);
        $result = $this->validate($postData, 'Order.getRepayplan');
        if ($result !== true) {
            errorResult($result);
        }

        //获取订单信息
        $orderModelObj = new orderModel();
        $orderData = $orderModelObj->getIdOrderInfo($postData['order_sn']);
        if (!$orderData) {
            errorResult('未获取订单数据');
        }
        //获取用户绑卡时间
        $userModelObj = new User();
        $userBankTime = $userModelObj->getUserBank($orderData['UserID']);
        //审核信息
        $approveInfo = $this->approveInfo($orderData);
        $bindCardInfo = $userModelObj->getUserAndBank($orderData['UserID']);
//      $lendingInfo = $this->lendingInfo($orderData);
        $lendingInfo['fail_reason'] = $orderData['fail_reason'];
        $lendingInfo['updated_at'] = strtotime($orderData['OpenTime']);
        //获取用户信息
        $user = Db::table('xb_mem_info')->where(['ID' => $orderData['UserID']])->find();
        $moneyConfirm['user_phone'] = $user['Mobile'];
        $temp = [
            'order_sn' => $orderData['OrderSn'], //订单唯一编号
            'order_status' => $this->handleOrderStatus($orderData['LoanStatus'],$user['isBank']), //订单状态 (处理后给立时贷的订单状态)
            'bindcard_time' => !empty($userBankTime['RenzTime']) ? strtotime($userBankTime['RenzTime']) : '', //绑卡时间（十位标准时时间戳） 绑卡后必传
            'approve_time' => !empty($orderData['ShTime']) ? strtotime($orderData['ShTime']) : '', //审批时间（十位标准时时间戳
            'confirm_time' => strtotime($orderData['OpenTime']), //确认用款时间（十位标准时时间戳）确认用款后必传
            'lending_time' => !empty($orderData['OpenTime']) ? strtotime($orderData['OpenTime']) : '', //放款时间（十位标准时时间戳）
            'remark' => '', //备注
            'approveInfo' => $approveInfo, //审核信息,审核后续状态必传
            'bindCardInfo' => $bindCardInfo, //绑卡信息,绑卡后续状态必传
            'moneyConfirm' => $moneyConfirm, //确认用款信息，确认用款后续状态必传
            'lendingInfo' => $lendingInfo, //放款信息，放款后续状态必传
        ];
        successResult($temp);
    }
    /**
     * 合同获取接口.
     */
    public function getContracts()
    {
        //验证参数
        $param = input('');
        $postData = json_decode($param['args'], 1);
        $result = $this->validate($postData, 'Order.getContracts');
        if ($result !== true) {
            errorResult($result);
        }
        $systemData = model('System')->getSystemInfo();

        $temp = [
            ['name' => $systemData['duanxinqianming'].' 代扣协议', 'link' => url('api/lishidai/agreement/withhold', '', 'html', $systemData['SystemDomain'])],
            ['name' => $systemData['duanxinqianming'].' 借款协议', 'link' => url('api/lishidai/agreement/loan', 'orderSn='.$postData['order_sn'], 'html', $systemData['SystemDomain'])],
        ];
        successResult($temp);
    }

    /**
     * 处理订单状态
     *
     * @param int $orderStatus 本系统订单状态值
     * @param integer $isBank 用户是否绑卡
     *
     * @return int 立时贷需要订单状态值
     *
     *  系统状态值
     *  0申请中 1等待放款 2已放款 3已完成 4已取消 5已拒绝 6等待银行打款 7待人工审核
     *
     *  立时贷状态值
     *  1待补充 2待审核 3待绑卡 4确认用款 5待签约 6待放款 7待提现(暂无) 8待还款 9审核失败 10已结清 11已失效 12签约失败 13还款中
     */
    private function handleOrderStatus($orderStatus,$isBank)
    {


        $status = 999;
        switch ($orderStatus) {
            case 0:
                $status = ($isBank == 1)?2:3;
                break;
            case 1:
                $status = 6;
                break;
            case 2:
                $status = 13;
                break;
            case 3:
                $status = 10;
                break;
            case 4:
                $status = 11;
                break;
            case 5:
                $status = 9;
                break;
            case 6:
                $status = 6;
                break;
            case 7:
                $status = 2;
                break;
		    case 11:
                $status = 11;
                break;		
        }
        return $status;
    }

    /**
     * 订单审核状态
     *
     * @param int $orderInfo
     *
     * @return array
     *               订单状态 0申请中 1等待放款 2已放款 3已完成 4已取消 5已拒绝 6等待银行打款 7待人工审核
     */
    public function approveInfo($orderInfo)
    {
        $temp = [];
        if (in_array($orderInfo['LoanStatus'], [1, 2, 3, 5, 6, 7])) {
            $temp = [
                'approve_amount' => $orderInfo['ApplyMoney'] * 100, //审批后的可借金额单位（分）
                'approve_term' => $orderInfo['ApplyDay'], //审批后的可借周期
                'term_type' => 1, //1:按天; 2：按月; 3：按年
                'approve_remark' => model('Order')->getOrderStatusDesc($orderInfo['LoanStatus']),
            ];
            //如果订单是审核失败 获取下次可再次申请借款的时间通知
            if ($orderInfo['LoanStatus'] == 5) {
                $days = (int) db('mem_info')->where(['ID' => $orderInfo['UserID']])->value('refuseDay');
                $refuseTime = date('Y-m-d H:i:s', strtotime($orderInfo['ShTime']) + ($days * 86400));
                $temp['can_loan_time'] = $refuseTime;
            }
        }
        return $temp;
    }

    /**
     * 验证订单是否已放款 是 返回订单数据.
     *
     * @param array $orderInfo 订单信息
     *
     * @return array
     */
    public function lendingInfo($orderInfo)
    {
        $temp = [];
        if ($orderInfo['LoanStatus'] == 2) {
            $temp = [
                'fail_reason' => '', //放款失败的说明信息
                'updated_at' => strtotime($orderInfo['OpenTime']),
            ];
        }

        return $temp;
    }
}
